<?php

namespace app\aiv110\controller;

use app\aiv110\controller\CommonController;
use think\Validate;
use think\Db;
use app\util\Utils;
use think\db\Expression;
use app\aiv110\model\SuperCard;
use app\aiv110\model\SuperCardYuyue;

class ExperienceController extends CommonController {
    /*
     * code列表
     */

    public function code() {
        /*
         * 0  成功
         * 1  参数错误
         * 2  验证失败
         * 130000 此订单不支持取消 
         * 130001 预约时间有误 
         * 130002 预约失败
         * 130003 该预约不可取消，如有疑问请联系400-801-3680 
         * 130004 取消失败 
         * 130004 该体验卡活动已结束
         * 130005 订单已退款
         */
    }

    /*
     * 体验卡详情
     * author xfwed 
     * date 2021.04.28
     * update 2021.05.10
     */

    public function experienceInfo() {
//        $data['img'] = 'http://47.104.83.107/images/kkmimg/kkmai/default/tiyankada.jpg'; //图片
//        $data['special_money'] = '98000'; //特权价
//        $data['cost_money'] = '128000'; //原价
        $id = input('param.id');
        $city_name = input('param.city_name');//用户所在的城市名
        if (empty($id)) {
            //查该城市最新的体验卡
            $row = SuperCard::where('find_in_set(:city_name,sell_city_name)', ['city_name' => $city_name])
                    ->where('status',1)
                    ->where('end_time','>',date('Y-m-d H:i:s'))
                    ->order('id desc')
                    ->find();
            //$id = SuperCard::SUPERCARD_DEFAULT_ID;
            $id = $row['id'];
        }
        $data = SuperCard::where('id', $id)
                ->field('id,name,price,special_price,sell_num,sell_num_base,content,img')
                ->find();
        if($data){
            return Utils::ajaxReturn(0, '查询成功', $data);
        }  else {
            return Utils::ajaxReturn(3, '您所选城市暂未开通体验卡服务，敬请期待！', null);
        }

    }

    /*
     * 体验卡结算页
     * author xfwed 
     * date 2021.05.10
     * 
     * @param int Ctm_id 用户id  必须
     */

    public function buyInfo() {
        $rule = [
            'card_id' => 'require|integer',
            'ctm_id' => 'require|integer',
            'city_name' => 'require',
        ];
        $msg = [
            'card_id.require' => '体验卡id必须',
            'card_id.integer' => '体验卡id为数字',
            'ctm_id.require' => '用户id必须',
            'ctm_id.integer' => '用户id为数字',
            'city_name.require' => '城市名必须',
        ];

        $all = input('param.');

        $validate = new Validate($rule, $msg);
        if (!$validate->check($all)) {
            $error = $validate->getError();
            return Utils::ajaxReturn(1, $error, null);
        }
        $card_id = $all['card_id'];
        if (empty($card_id)) {
            $card_id = SuperCard::SUPERCARD_DEFAULT_ID;
        }
        $ctm_id = $all['ctm_id'];
        $city_name = $all['city_name'];
//        $city_names = Db::table('sys_dictionary')
//                ->where('type', 'EXPERIENCE_CITY_NAMES')
//                ->value('view');
//        $city_names = explode(',', $city_names);

        $superCardRow = SuperCard::where('id', $card_id)
                ->field('id,name,img,price,special_price,limit_num,note,if_redmoney,end_time,status,sell_city_name')
                ->find();
        $city_names = explode(',', $superCardRow['sell_city_name']);
        $end_time = strtotime($superCardRow['end_time']) + 24 * 60 * 60;
        if ($end_time < time()) {
            return Utils::ajaxReturn(130004, '该体验卡活动已结束', null);
        }
        if ($superCardRow['status'] == 2) {
            return Utils::ajaxReturn(130004, '该体验卡活动已下架', null);
        }

        if (in_array($city_name, $city_names)) {
            $row = Db::name('super_card_order')
                    ->where('ctm_id', $ctm_id)
                    ->where('status', '>=', 2)
                    ->where('card_id',$card_id)
                    ->count();
            if ($row >= $superCardRow['limit_num']) {
                return Utils::ajaxReturn(3, '该体验卡每个账号限购' . $superCardRow['limit_num'] . '次', null);
            } else {
                return Utils::ajaxReturn(0, '查询成功', $superCardRow);
            }
        } else {
            return Utils::ajaxReturn(3, '您所选城市暂未开通体验卡服务，敬请期待！', null);
        }
    }

    /*
     * 判断限购（下单前调）
     * author xfwed 
     * date 2021.04.28
     * 
     * @param int Ctm_id 用户id  必须
     */

    public function limitBuy() {
        $rule = [
            'ctm_id' => 'require|integer',
            'city_name' => 'require',
        ];
        $msg = [
            'ctm_id.require' => '用户id必须',
            'ctm_id.integer' => '用户id为数字',
            'city_name.require' => '城市名必须',
        ];

        $all = input('param.');

        $validate = new Validate($rule, $msg);
        if (!$validate->check($all)) {
            $error = $validate->getError();
            return Utils::ajaxReturn(1, $error, null);
        }
        $ctm_id = $all['ctm_id'];
        $city_name = $all['city_name'];
        $city_names = Db::table('sys_dictionary')
                ->where('type', 'EXPERIENCE_CITY_NAMES')
                ->value('view');
        $city_names = explode(',', $city_names);

        if (in_array($city_name, $city_names)) {
            $row = Db::name('super_card_order')
                    ->where('ctm_id', $ctm_id)
                    ->where('status', 2)
                    ->find();
            if ($row) {
                $data['is_buy'] = 2; //1是2否可以购买
            } else {
                $data['is_buy'] = 1; //1是2否可以购买
            }
        } else {
            $data['is_buy'] = 3; //1是2否可以购买3该城市没有开放
        }

        return Utils::ajaxReturn(0, '查询成功', $data);
    }

    /*
     * 发送短信（支付成功后调）
     * author xfwed 
     * date 2021.04.28
     * @param int Ctm_id 用户id  必须
     */

    public function sendMessage() {
        $rule = [
            'id' => 'require',
        ];
        $msg = [
            'id.require' => '订单id必须',
        ];

        $all = input('param.');

        $validate = new Validate($rule, $msg);
        if (!$validate->check($all)) {
            $error = $validate->getError();
            return Utils::ajaxReturn(1, $error, null);
        }
        $id = $all['id'];
        $row = Db::name('super_card_order')
                ->where('order_no', $id)
                ->where('status', 2)
                ->find();
        if (empty($row)) {
            return Utils::ajaxReturn(3, '没有发现此订单', null);
        }
        $custom_phone = Db::name('custom')
                ->where('id', $row['ctm_id'])
                ->value('custom_phone');
        $content = '您购买的体验卡已付款，您可在5月25日后，打开DAVID KKM的微信小程序，在“我的-体验卡订单”中预约服务！客服4008013680';
        Utils::sendSms($custom_phone, $content);

        return Utils::ajaxReturn(0, '发送成功', null);
    }

    /*
     * 回调接口（盼丰在回调接口里面调）
     * author xfwed 
     * date 2021.05.12
     * 1.修改订单状态
     * 2.插入预约表和预约copy表
     * 3.插入销售入账（店铺、美容师、平台）
     * 4.发送通知短信
     */

    public function paySuccess() {
        $rule = [
            'id' => 'require',
        ];
        $msg = [
            'id.require' => '订单id必须',
        ];

        $all = input('param.');

        $validate = new Validate($rule, $msg);
        if (!$validate->check($all)) {
            $error = $validate->getError();
            return Utils::ajaxReturn(1, $error, null);
        }
        $id = $all['id'];
        $row = Db::name('super_card_order')
                ->where('id', $id)
                ->where('status', 1)
                ->where('pay_status',2)
                ->find();
        if (empty($row)) {
            return Utils::ajaxReturn(3, '没有发现此订单', null);
        }

        Db::startTrans();
        //1.修改订单状态
        $saveOrder = Db::name('super_card_order')
                ->where('id', $id)
                ->update(['status' => 2, 'pay_time' => date('Y-m-d H:i:s'), 'pay_status' => 2]);
        //2.插入预约表和预约copy表
        $card_id = $row['card_id']; //购买的体验卡id
        $cardRow = Db::name('super_card')
                ->where('id', $card_id)
                ->find();
        $cardItemList = Db::name('super_card_item')
                ->where('card_id', $card_id)
                ->select();
        if ($row['real_money'] == $cardRow['price']) {
            $price_type = 1; //按照原价分配
        } elseif ($row['real_money'] == $cardRow['special_price']) {
            $price_type = 2; //按照特权价分配
        }
        foreach ($cardItemList as $key => $value) {
            for ($i = 0; $i < $value['ser_num']; $i++) {
                if ($price_type == 1) {
                    $money = $value['price'] / $value['ser_num'];
                } elseif ($price_type == 2) {
                    $money = $value['special_price'] / $value['ser_num'];
                }
                $oneData = [
                    'order_id' => $id,
                    'item_id' => $value['id'],
                    'money' => $money,
                    'factory_per' => $value['factory_per'],
                    'staff_per' => $value['staff_per'],
                    'store_per' => $value['store_per'],
                    'sell_per' => $value['sell_per'],
                    'kkm_per' => $value['kkm_per'],
                    'add_time' => date('Y-m-d H:i:s'),
                ];
                $insertYuyue = Db::name('super_card_yuyue')->insertGetId($oneData);
                $oneData['yuyue_id'] = $insertYuyue;
                $insertYuyueCopy = Db::name('super_card_yuyue_copy')->insertGetId($oneData);
            }
        }
        //3.插入销售入账（店铺、美容师、平台）
        $enjoy_id = $row['enjoy_id'];
        if ($row['enjoy_type'] == 0) {//0平台 1.美容师 2.店铺 3.用户
            //平台的销售流水  在最终活动结束分账的时候才插入
//            $allmoney = $row['real_money']-$row['red_money'];
//            $last_money = Db::name('kkm_flow')->order('id desc')->value('last_money');
//            $last_money = $last_money + $allmoney*($cardRow['sell_per']/100);
//            $flowData['order_id'] = $id;
//            $flowData['item_name'] = '体验卡-'.$cardRow['name'];
//            $flowData['type'] = 1;
//            $flowData['pro_type'] = 20;
//            $flowData['allmoney'] = $allmoney;
//            $flowData['money'] = $allmoney*($cardRow['sell_per']/100);
//            $flowData['last_money'] = $last_money;
//            $flowData['add_time'] = date('Y-m-d H:i:s');
//            $insertFlow = Db::name('kkm_flow')->insert($flowData);
            $insertFlow = TRUE;
        } elseif ($row['enjoy_type'] == 1) {
            $allmoney = $row['real_money'] - $row['red_money'];
            $flowData['order_id'] = $id;
            $flowData['item_name'] = '体验卡-' . $cardRow['name'];
            $flowData['type'] = 1;
            $flowData['pro_type'] = 20;
            $flowData['staff_id'] = $enjoy_id;
            $flowData['all_money'] = $allmoney;
            $flowData['money'] = $allmoney * ($cardRow['sell_per'] / 100);
            $flowData['ctm_id'] = $row['ctm_id'];
            $flowData['ctm_name'] = Db::name('custom')->where('id', $row['ctm_id'])->value('custom_name');
            $flowData['ctm_photo'] = Db::name('custom')->where('id', $row['ctm_id'])->value('custom_photo');
            $flowData['status'] = 0;
            $flowData['add_time'] = date('Y-m-d H:i:s');
            $insertFlow = Db::name('staff_flow_new')->insert($flowData);
        } elseif ($row['enjoy_type'] == 2) {
            $allmoney = $row['real_money'] - $row['red_money'];
            $last_money = Db::name('store_flow_copy')->where('store_id', $enjoy_id)->order('id desc')->value('last_money');
            $last_money = $last_money + $allmoney * ($cardRow['sell_per'] / 100);
            $flowData['order_id'] = $id;
            $flowData['item_name'] = '体验卡-' . $cardRow['name'];
            $flowData['type'] = 1;
            $flowData['pro_type'] = 20;
            $flowData['store_id'] = $enjoy_id;
            $flowData['allmoney'] = $allmoney;
            $flowData['money'] = $allmoney * ($cardRow['sell_per'] / 100);
            $flowData['last_money'] = $last_money;
            $flowData['add_time'] = date('Y-m-d H:i:s');
            $insertFlow = Db::name('store_flow_copy')->insert($flowData);
        }
        //4.发送通知短信
        $custom_phone = Db::name('custom')
                ->where('id', $row['ctm_id'])
                ->value('custom_phone');
        $content = '您购买的体验卡已付款，您可在5月25日后，打开DAVID KKM的微信小程序，在“我的-体验卡订单”中预约服务！客服4008013680';
        Utils::sendSms($custom_phone, $content);
        
        //5.增加销量
        $saveSuperCard = Db::name('super_card')
                ->where('id', $card_id)
                ->setInc('sell_num');

        if ($saveOrder && $insertYuyue && $insertYuyueCopy && $insertFlow && $saveSuperCard) {
            Db::commit();
            return Utils::ajaxReturn(0, '成功', null);
        } else {
            Db::rollback();
            return Utils::ajaxReturn(30008, '失败', null);
        }
    }

    /*
     * 体验卡订单
     * author xfwed 
     * date 2021.05.13
     * 
     * @param int perPage 每页数量 非必须，默认20
     * @param int page 当前页数 非必须，默认0
     */

    public function superCardOrderList() {
        $rule = [
            'ctm_id' => 'require',
            'status' => 'require',
            'perPage' => 'integer|egt:1',
            'page' => 'integer|egt:0',
        ];
        $msg = [
            'ctm_id.require' => '用户id必须',
            'status.require' => '分类必须',
            'perPage.integer' => '每页数量为数字',
            'perPage.egt' => '每页数量最小为1',
            'page.integer' => '页数为数字',
            'page.egt' => '页数最小为0',
        ];

        $all = input('param.');

        $validate = new Validate($rule, $msg);
        if (!$validate->check($all)) {
            $error = $validate->getError();
            return Utils::ajaxReturn(1, $error, null);
        }

        $ctm_id = $all['ctm_id'];
        $status = $all['status']; //0全部1待付款2待预约3待服务4已完成5已取消
        if ($status) {
            if ($status == 5) {
                $where['sco.status'] = 0;
            } else {
                $where['sco.status'] = $status;
            }
        }

        $perPage = isset($all['perPage']) ? $all['perPage'] : 20;
        $page = isset($all['page']) ? $all['page'] : 0;
        if ($page == 0) {
            $page = 1;
        }

        $offset = ($page - 1) * $perPage; //->limit($offset, $perPage)

        $where['sco.ctm_id'] = $ctm_id;
        $list = Db::name('super_card_order')
                ->alias('sco')
                ->join('super_card sc', 'sc.id = sco.card_id', 'left')
                ->order('sco.add_time desc')
                ->where($where)
                ->field('sco.id,sco.order_no,sco.real_money,sco.pay_money,sco.balance_money,sco.red_money,sco.status,sco.num,sco.prepay_id,sc.name,sc.img,sc.price')
                ->limit($offset, $perPage)
                ->select();

        return Utils::ajaxReturn(0, '查询成功', $list);
    }

    /*
     * 体验卡订单详情
     * author xfwed 
     * date 2021.05.13
     */

    public function superCardOrderInfo() {
        $rule = [
            'id' => 'require|integer',
        ];
        $msg = [
            'id.require' => '体验卡订单id必须',
            'id.integer' => '体验卡订单id为数字',
        ];

        $all = input('param.');

        $validate = new Validate($rule, $msg);
        if (!$validate->check($all)) {
            $error = $validate->getError();
            return Utils::ajaxReturn(1, $error, null);
        }

        $id = $all['id'];
        $where['sco.id'] = $id;

        $row = Db::name('super_card_order')
                ->alias('sco')
                ->join('super_card sc', 'sc.id = sco.card_id', 'left')
                ->where($where)
                ->field('sco.id,sco.card_id,sco.order_no,sco.real_money,sco.pay_money,sco.balance_money,sco.red_money,sco.status,sco.num,sco.prepay_id,sco.pay_time,sco.add_time,sc.name,sc.img,sc.price')
                ->find();
        //查询预约列表
        $yuyueList = Db::name('super_card_yuyue')
                ->alias('scy')
                ->join('super_card_item sci', 'sci.id = scy.item_id', 'left')
                ->where('scy.order_id', $id)
                ->field('scy.id,scy.status,sci.item_name')
                ->select();
        $row['yuyueList'] = $yuyueList;
        $row['yuyueNum'] = count($yuyueList);
        $row['yuyuesheng'] = Db::name('super_card_yuyue')
                ->where('order_id', $id)
                ->where('status', 'not in', '3,4')
                ->count();

        return Utils::ajaxReturn(0, '查询成功', $row);
    }

    /*
     * 取消体验卡订单
     * author xfwed 
     * date 2021.05.13
     */

    public function cancelSuperCardOrder() {
        $rule = [
            'id' => 'require|integer',
        ];
        $msg = [
            'id.require' => '体验卡订单id必须',
            'id.integer' => '体验卡订单id为数字',
        ];

        $all = input('param.');

        $validate = new Validate($rule, $msg);
        if (!$validate->check($all)) {
            $error = $validate->getError();
            return Utils::ajaxReturn(1, $error, null);
        }

        $id = $all['id'];

        $row = Db::name('super_card_order')
                ->where('id', $id)
                ->field('id,status')
                ->find();
        if ($row['status'] != 1) {
            return Utils::ajaxReturn(130000, '此订单不支持取消', NULL);
        }

        $relust = Db::name('super_card_order')
                ->where('id', $id)
                ->update(['status' => 0, 'cancel_time' => date('Y-m-d H:i:s')]);
        if ($relust) {
            return Utils::ajaxReturn(0, '取消成功', null);
        } else {
            return Utils::ajaxReturn(3, '取消失败', null);
        }
    }

    /*
     * 去预约
     * author xfwed 
     * date 2021.05.14
     */

    public function yuyuePage() {
        $rule = [
            'order_id' => 'require|integer',
        ];
        $msg = [
            'order_id.require' => '体验卡订单id必须',
            'order_id.integer' => '体验卡订单id为数字',
        ];

        $all = input('param.');

        $validate = new Validate($rule, $msg);
        if (!$validate->check($all)) {
            $error = $validate->getError();
            return Utils::ajaxReturn(1, $error, null);
        }

        $order_id = $all['order_id']; //体验卡订单id
        $yuyue_id = input('param.yuyue_id'); //预约id  如果传此字段 返回此子项目 否则返回该订单随机一个待预约

        if ($yuyue_id) {
            $row = Db::name('super_card_yuyue')
                    ->alias('scy')
                    ->join('super_card_item sci', 'sci.id = scy.item_id', 'left')
                    ->where('scy.id', $yuyue_id)
                    ->field('scy.id,sci.item_name')
                    ->find();
        } else {
            $row = Db::name('super_card_yuyue')
                    ->alias('scy')
                    ->join('super_card_item sci', 'sci.id = scy.item_id', 'left')
                    ->where('scy.order_id', $order_id)
                    ->where('scy.status', 'in', '1,5,6,7')
                    ->order('scy.add_time desc')
                    ->field('scy.id,sci.item_name')
                    ->find();
        }
        if ($row) {
            return Utils::ajaxReturn(0, '查询成功', $row);
        } else {
            return Utils::ajaxReturn(3, '查询失败', null);
        }
    }

    /*
     * 选择服务项目
     * author xfwed 
     * date 2021.05.14
     */

    public function selectYuyueItem() {
        $rule = [
            'order_id' => 'require|integer',
        ];
        $msg = [
            'order_id.require' => '体验卡订单id必须',
            'order_id.integer' => '体验卡订单id为数字',
        ];

        $all = input('param.');

        $validate = new Validate($rule, $msg);
        if (!$validate->check($all)) {
            $error = $validate->getError();
            return Utils::ajaxReturn(1, $error, null);
        }

        $order_id = $all['order_id']; //体验卡订单id
        $list = Db::name('super_card_yuyue')
                ->alias('scy')
                ->join('super_card_item sci', 'sci.id = scy.item_id', 'left')
                ->where('scy.order_id', $order_id)
                ->where('scy.status', 'in', '1,5,6,7')
                ->order('scy.add_time desc')
                ->field('scy.id,sci.item_name')
                ->select();
        return Utils::ajaxReturn(0, '查询成功', $list);
    }

    /*
     * 选择服务时间和门店
     * author xfwed 
     * date 2021.05.14
     */

    public function selectYuyueTime() {
        $rule = [
            'yuyue_id' => 'require|integer',
        ];
        $msg = [
            'yuyue_id.require' => '预约id必须',
            'yuyue_id.integer' => '预约id为数字',
        ];

        $all = input('param.');

        $validate = new Validate($rule, $msg);
        if (!$validate->check($all)) {
            $error = $validate->getError();
            return Utils::ajaxReturn(1, $error, null);
        }

        $yuyue_id = $all['yuyue_id']; //预约id
        $item_id = Db::name('super_card_yuyue')
                ->where('id', $yuyue_id)
                ->value('item_id');
        $storeList = Db::name('super_card_yuyue_time')
                ->alias('scyt')
                ->join('store s', 's.id = scyt.store_id', 'left')
                ->where('scyt.card_item_id', $item_id)
                ->where('scyt.yuyue_date','>=',date('Y-m-d'))
                ->group('scyt.store_id')
                ->field('s.id,s.store_name,s.store_address,s.longitude,s.latitude')
                ->select();
        foreach ($storeList as $k => $v) {
            $list = Db::name('super_card_yuyue_time')
                    ->where('card_item_id', $item_id)
                    ->where('store_id', $v['id'])
                    ->where('yuyue_date','>=',date('Y-m-d'))
                    ->order('yuyue_date asc')
                    ->field('id,yuyue_date,time1_num,time2_num,time3_num,time1_surplus_num,time2_surplus_num,time3_surplus_num')
                    ->select();
            $storeList[$k]['list'] = $list;
        }

        return Utils::ajaxReturn(0, '查询成功', $storeList);
    }

    /*
     * 体验卡预约
     * author xfwed 
     * date 2021.05.17
     */

    public function yuyue() {
        $rule = [
            'yuyue_id' => 'require|integer',
            'yuyue_date' => 'require',
            'yuyue_time' => 'require',
            'store_id' => 'require',
        ];
        $msg = [
            'yuyue_id.require' => '预约id必须',
            'yuyue_id.integer' => '预约id为数字',
            'yuyue_date.require' => '预约日期必须',
            'yuyue_time.require' => '预约时间必须',
            'store_id.require' => '店铺id必须',
        ];

        $all = input('param.');

        $validate = new Validate($rule, $msg);
        if (!$validate->check($all)) {
            $error = $validate->getError();
            return Utils::ajaxReturn(1, $error, null);
        }

        $yuyue_id = $all['yuyue_id']; //预约id
        $yuyue_date = $all['yuyue_date']; //预约日期
        $yuyue_time = $all['yuyue_time']; //预约时间
        $store_id = $all['store_id']; //店铺id
        $note = input('param.note'); //用户预约备注

        $cardRow = Db::name('super_card_yuyue')
                ->where('id', $yuyue_id)
                ->field('item_id,order_id')
                ->find();
        $order_id = $cardRow['order_id'];
        $orderRow = Db::name('super_card_order')
                ->where('id',$order_id)
                ->field('status')
                ->find();
        if($orderRow['status'] == 5){
            return Utils::ajaxReturn(130005, '订单已退款', null);
        }
        $item_id = $cardRow['item_id'];
        //判断预约时间是否可用
        if ($yuyue_time == 1) {
            $where['time1_surplus_num'] = ['>', 0];
            $a = 'time1_surplus_num';
        } elseif ($yuyue_time == 2) {
            $where['time2_surplus_num'] = ['>', 0];
            $a = 'time2_surplus_num';
        } elseif ($yuyue_time == 3) {
            $where['time3_surplus_num'] = ['>', 0];
            $a = 'time3_surplus_num';
        }
        $superCardYuyueTimeRow = Db::name('super_card_yuyue_time')
                ->where('store_id', $store_id)
                ->where('card_item_id', $item_id)
                ->where('yuyue_date', $yuyue_date)
                ->where($where)
                ->find();
        if (empty($superCardYuyueTimeRow)) {
            return Utils::ajaxReturn(130001, '预约时间有误', null);
        }
        Db::startTrans();
        //1.修改预约表
        $ser_code = SuperCardYuyue::generateSerCode();
        $saveYuyueData['status'] = 2;
        $saveYuyueData['store_id'] = $store_id;
        $saveYuyueData['yuyue_date'] = $yuyue_date;
        $saveYuyueData['yuyue_time'] = $yuyue_time;
        $saveYuyueData['ser_code'] = $ser_code;
        $saveYuyueData['note'] = $note;
        $saveYuyueData['handle_yuyue_time'] = date('Y-m-d H:i:s');
        $saveYuyue = Db::name('super_card_yuyue')
                ->where('id', $yuyue_id)
                ->update($saveYuyueData);
        //2.复制预约copy表
        $yuYueCopyData = Db::name('super_card_yuyue')
                ->where('id', $yuyue_id)
                ->field('id,add_time', TRUE)
                ->find();
        $yuYueCopyData['yuyue_id'] = $yuyue_id;
        $yuYueCopyData['add_time'] = date('Y-m-d H:i:s');
        $insertYuyueCopy = Db::name('super_card_yuyue_copy')
                ->insert($yuYueCopyData);
        //3.修改订单状态
        $saveOrder = SuperCardYuyue::saveOrderStatus($yuyue_id);
        //4.修改预约时间表
        $saveSuperCardYuyueTime = Db::name('super_card_yuyue_time')
                ->where('store_id', $store_id)
                ->where('card_item_id', $item_id)
                ->where('yuyue_date', $yuyue_date)
                ->setDec($a);
        if ($saveYuyue && $insertYuyueCopy && $saveOrder && $saveSuperCardYuyueTime) {
            Db::commit();
            return Utils::ajaxReturn(0, '预约成功', null);
        } else {
            Db::rollback();
            return Utils::ajaxReturn(130002, '预约失败', null);
        }
    }

    /*
     * 体验卡预约详情
     * author xfwed 
     * date 2021.05.18
     */

    public function yuyueInfo() {
        $rule = [
            'yuyue_id' => 'require|integer',
        ];
        $msg = [
            'yuyue_id.require' => '预约id必须',
            'yuyue_id.integer' => '预约id为数字',
        ];

        $all = input('param.');

        $validate = new Validate($rule, $msg);
        if (!$validate->check($all)) {
            $error = $validate->getError();
            return Utils::ajaxReturn(1, $error, null);
        }

        $yuyue_id = $all['yuyue_id']; //预约id

        $yuyueRow = Db::name('super_card_yuyue')
                ->alias('scy')
                ->join('super_card_item sci', 'sci.id =scy.item_id', 'left')
                ->join('store s', 's.id= scy.store_id', 'left')
                ->where('scy.id', $yuyue_id)
                ->field('scy.id,scy.status,scy.yuyue_date,scy.yuyue_time,scy.ser_code,sci.item_name,s.store_name,s.store_address,s.longitude,s.latitude')
                ->find();
        //查询预约轨迹
        $list = Db::name('super_card_yuyue_copy')
                ->alias('scyc')
                ->join('store s', 's.id = scyc.store_id', 'left')
                ->where('scyc.yuyue_id', $yuyue_id)
                ->where('scyc.status', 'in', '5,6,7')
                ->field('s.store_name,s.store_address,s.longitude,s.latitude,scyc.id,scyc.status,scyc.yuyue_date,scyc.yuyue_time')
                ->select();
        $yuyueRow['list'] = $list;

        return Utils::ajaxReturn(0, '查询成功', $yuyueRow);
    }

    /*
     * 取消体验卡预约
     * author xfwed 
     * date 2021.05.18
     */

    public function cancelYuYue() {
        $rule = [
            'yuyue_id' => 'require|integer',
        ];
        $msg = [
            'yuyue_id.require' => '预约id必须',
            'yuyue_id.integer' => '预约id为数字',
        ];

        $all = input('param.');

        $validate = new Validate($rule, $msg);
        if (!$validate->check($all)) {
            $error = $validate->getError();
            return Utils::ajaxReturn(1, $error, null);
        }

        $yuyue_id = $all['yuyue_id']; //预约id
        $cancel_why = input('param.cancel_why'); //取消原因

        $superCardYuyueRow = Db::name('super_card_yuyue')
                ->where('id', $yuyue_id)
                ->find();
        //判断是否可以取消
        if ($superCardYuyueRow['status'] != 2) {
            return Utils::ajaxReturn(130003, '该预约不可取消，如有疑问请联系400-801-3680', null);
        }
        Db::startTrans();
        //1.修改预约状态
        $saveYuyueData['status'] = 6;
        $saveYuyueData['cancel_time'] = date('Y-m-d H:i:s');
        $saveYuyueData['cancel_why'] = $cancel_why;
        $saveYuyue = Db::name('super_card_yuyue')
                ->where('id', $yuyue_id)
                ->update($saveYuyueData);
        //2.复制预约copy表
        $yuYueCopyData = Db::name('super_card_yuyue')
                ->where('id', $yuyue_id)
                ->field('id,add_time', TRUE)
                ->find();
        $yuYueCopyData['yuyue_id'] = $yuyue_id;
        $yuYueCopyData['add_time'] = date('Y-m-d H:i:s');
        $insertYuyueCopy = Db::name('super_card_yuyue_copy')
                ->insert($yuYueCopyData);
        //3.修改订单状态
        $saveOrder = SuperCardYuyue::saveOrderStatus($yuyue_id);
        //4.修改预约时间表
        $yuyue_time = $superCardYuyueRow['yuyue_time'];
        if ($yuyue_time == 1) {
            $a = 'time1_surplus_num';
        } elseif ($yuyue_time == 2) {
            $a = 'time2_surplus_num';
        } elseif ($yuyue_time == 3) {
            $a = 'time3_surplus_num';
        }
        $saveSuperCardYuyueTime = Db::name('super_card_yuyue_time')
                ->where('store_id', $superCardYuyueRow['store_id'])
                ->where('card_item_id', $superCardYuyueRow['item_id'])
                ->where('yuyue_date', $superCardYuyueRow['yuyue_date'])
                ->setInc($a);
        if ($saveYuyue && $insertYuyueCopy && $saveOrder && $saveSuperCardYuyueTime) {
            Db::commit();
            return Utils::ajaxReturn(0, '取消成功', null);
        } else {
            Db::rollback();
            return Utils::ajaxReturn(130004, '取消失败', null);
        }
    }

    /*
     * 体验卡预约超时
     * author xfwed 
     * date 2021.05.21
     */

    public function timeOutYuYue() {
        $list = Db::name('super_card_yuyue')
                ->where('status', 2)
                ->where('yuyue_date', '<=', date('Y-m-d'))
                ->select();
        foreach ($list as $k => $v) {
            $yuyue_id = $v['id'];
            $yuyue_date = $v['yuyue_date']; //预约时间	
            $yuyue_time = $v['yuyue_time']; //预约时间 1上午9-1点 2下午1-6点 3晚上6-9点
            if ($yuyue_time == 1) {
                $a = 'time1_surplus_num';
                $yuyue_end = strtotime($yuyue_date) + 13 * 60 * 60;
            } elseif ($yuyue_time == 2) {
                $a = 'time2_surplus_num';
                $yuyue_end = strtotime($yuyue_date) + 18 * 60 * 60;
            } elseif ($yuyue_time == 3) {
                $a = 'time3_surplus_num';
                $yuyue_end = strtotime($yuyue_date) + 21 * 60 * 60;
            }

            if ($yuyue_end < time()) {//预约超时了
                Db::startTrans();
                //1.修改预约状态
                $saveYuyueData['status'] = 5;
                $saveYuyue = Db::name('super_card_yuyue')
                        ->where('id', $yuyue_id)
                        ->update($saveYuyueData);
                //2.复制预约copy表
                $yuYueCopyData = Db::name('super_card_yuyue')
                        ->where('id', $yuyue_id)
                        ->field('id,add_time', TRUE)
                        ->find();
                $yuYueCopyData['yuyue_id'] = $yuyue_id;
                $yuYueCopyData['add_time'] = date('Y-m-d H:i:s');
                $insertYuyueCopy = Db::name('super_card_yuyue_copy')
                        ->insert($yuYueCopyData);
                //3.修改订单状态
                $saveOrder = SuperCardYuyue::saveOrderStatus($yuyue_id);
                //4.修改预约时间表
                $saveSuperCardYuyueTime = Db::name('super_card_yuyue_time')
                        ->where('store_id', $v['store_id'])
                        ->where('card_item_id', $v['item_id'])
                        ->where('yuyue_date', $v['yuyue_date'])
                        ->setInc($a);
                if ($saveYuyue && $insertYuyueCopy && $saveOrder && $saveSuperCardYuyueTime) {
                    Db::commit();
                } else {
                    Db::rollback();
                }
            }
        }
    }

}
